import {defineStore} from "pinia";
import {ref, markRaw, computed} from 'vue';

// 按需导入所需icon图标
import {Dashboard, Navigation, Page, Peoples, IdCardH, Permissions, Me, User} from "@icon-park/vue-next";
import {ElMessage} from "element-plus";
import {MENU_PERMISSIONS} from '@/constants/permissions.js'
import { useUserStore } from '@/stores/pages/user.js'; // 提前导入 useUserStore


// 定义默认菜单数据
const defaultMenuList = [
    {
        index: '/app/dashboard',
        title: '仪表盘',
        icon: markRaw(Dashboard),//markRaw：阻止对象被响应式转换，不会影响组件的正常使用，避免Vue对组件对象进行不必要响应式处理，提升运行效率
        iconProps: {theme: 'outline', fill: '#fff'},
        ...MENU_PERMISSIONS.DASHBOARD
    },
    {
        index: '/PermissionsManagement',
        title: '权限管理',
        icon: markRaw(Permissions),
        iconProps: {theme: 'outline', fill: '#fff'},
        ...MENU_PERMISSIONS.USER_MANAGEMENT,
        children: [
            {
                index: '/app/UserManagement',
                title: '用户管理',
                icon: markRaw(Peoples),
                iconProps: {theme: 'outline', fill: '#fff'},
                ...MENU_PERMISSIONS.USER_MANAGEMENT
            },
            {
                index: '/app/RoleManagement',
                title: '角色管理',
                icon: markRaw(IdCardH),
                iconProps: {theme: 'outline', fill: '#fff'},
                ...MENU_PERMISSIONS.ROLE_MANAGEMENT
            }
        ]
    },
    {
        index: '/PersonalCenter',
        title: '个人中心',
        icon: markRaw(Me),
        iconProps: {theme: 'outline', fill: '#fff'},
        ...MENU_PERMISSIONS.PERSONAL_SETTINGS,
        children: [
            {
                index: '/app/PersonalSettings',
                title: '个人设置',
                icon: markRaw(User),
                iconProps: {theme: 'outline', fill: '#fff'},
                ...MENU_PERMISSIONS.PERSONAL_SETTINGS
            }
        ]
    },
    {
        index: '/nav1',
        title: '导航一',
        icon: markRaw(Navigation),
        iconProps: {theme: 'outline', fill: '#fff'},
        children: [
            {
                index: '/app/view1',
                title: '页面1',
                icon: markRaw(Page),
                iconProps: {theme: 'outline', fill: '#fff'}
            },
            {
                index: '/app/view2',
                title: '页面2',
                icon: markRaw(Page),
                iconProps: {theme: 'outline', fill: '#fff'}
            },
            {
                index: '/app/view3',
                title: '页面3',
                icon: markRaw(Page),
                iconProps: {theme: 'outline', fill: '#fff'}
            },
        ]
    }
]


/**
 * 菜单过滤函数
 * @param {Array} menuItems - 菜单项数组
 * @param {Array} userRoles - 用户角色数组
 * @param {Function} hasPermission - 权限检查函数
 * @returns {Array} 过滤后的菜单数组
 */
const filterMenuByPermission = (menuItems, userRoles, hasPermission) => {
    return menuItems.filter(item => {
        // 检查角色权限 - 如果没有设置roles，默认可见
        if (item.roles && !item.roles.some(role => userRoles.includes(role))) {
            return false
        }

        // 检查具体权限点 - 如果没有设置permission，默认可见
        if (item.permission && !hasPermission(item.permission)) {
            return false
        }

        // 递归处理子菜单
        if (item.children) {
            item.children = filterMenuByPermission(item.children, userRoles, hasPermission);
            // 如果过滤后子菜单为空，但父菜单本身有权限，则保留父菜单（不强制删除）
        }

        return true
    })
}

export const useMenuStore = defineStore('menu', () => {
    const menuList = ref([...defaultMenuList]);

    // 计算属性：获取过滤后的菜单
    const filteredMenuList = computed(() => {
        const userStore = useUserStore();

        if (!userStore.isAuthenticated) {
            return []; // 未登录时返回空菜单
        }

        const userRoles = userStore.getUserRoles();
        const hasPermission = (permission) => userStore.hasPermission(permission);

        return filterMenuByPermission([...defaultMenuList], userRoles, hasPermission)
    })

    // 加载菜单数据
    const loadMenuList = async () => {
        try {
            // (1).API调用获取菜单数据
            // const response = await request.get('/api/menus');
            // menuList.value = response.data;

            // (2).使用默认数据 + 权限过滤

            const userStore = useUserStore();

            const userRoles = userStore.getUserRoles();
            const hasPermission = (permission) => userStore.hasPermission(permission);

            menuList.value = filterMenuByPermission([...defaultMenuList], userRoles, hasPermission);

        } catch (error) {
            console.error('加载菜单数据失败:', error);
            ElMessage.error('加载菜单数据失败')

            // 出错时使用过滤后的默认菜单数据
            const userStore = useUserStore();

            const userRoles = userStore.getUserRoles();
            const hasPermission = (permission) => userStore.hasPermission(permission);
            menuList.value = filterMenuByPermission([...defaultMenuList], userRoles, hasPermission);
        }
    };

    // 添加菜单项
    const addMenuItem = (item) => {
        try {
            const userStore = useUserStore();

            // 检查当前用户是否有权限添加这个菜单项
            const userRoles = userStore.getUserRoles();
            const hasPermission = (permission) => userStore.hasPermission(permission);

            if (item.roles && !item.roles.some(role => userRoles.includes(role))) {
                ElMessage.error('没有权限添加此菜单项');
                return;
            }

            if (item.permission && !hasPermission(item.permission)) {
                ElMessage.error('没有权限添加此菜单项');
                return;
            }

            // 确保图标被标记为非响应式
            if (item.icon) {
                item.icon = markRaw(item.icon);
            }

            menuList.value.push(item);
        } catch (error) {
            console.error('添加菜单项失败:', error);
            ElMessage.error('添加菜单项失败');
        }
    };

    // 更新菜单项
    const updateMenuItem = (index, newItem) => {
        try {
            const itemIndex = menuList.value.findIndex(item => item.index === index);
            if (itemIndex !== -1) {
                // 确保图标被标记为非响应式
                if (newItem.icon) {
                    newItem.icon = markRaw(newItem.icon);
                }
                menuList.value[itemIndex] = newItem;
            }
        } catch (error) {
            console.error('更新菜单项失败:', error);
            ElMessage.error('更新菜单项失败')
        }
    };

    // 删除菜单项
    const removeMenuItem = (index) => {
        try {
            const itemIndex = menuList.value.findIndex(item => item.index === index);
            if (itemIndex !== -1) {
                menuList.value.splice(itemIndex, 1);
            }
        } catch (error) {
            console.error('删除菜单项失败:', error);
            ElMessage.error('删除菜单项失败')
        }
    };

    // 刷新菜单（权限变更后调用）
    const refreshMenu = () => {
        loadMenuList();
    };

    return {
        menuList,
        filteredMenuList,
        loadMenuList,
        addMenuItem,
        updateMenuItem,
        removeMenuItem,
        refreshMenu
    }
})